var optType = 1, optIndex = 0, optRow = null, menuData = null;

var config = {
    table: {
        title: '角色数据列表',
        toolbar:'#table-auth-btn',
        height: kit.wh().height - 40,
        singleSelect: true,
        pagination: false,
        onClickRow:function () {
            optRow = component.datagrid.getRowData('#table-list');
            optIndex = component.datagrid.getDataRow('#table-list');
        },
        columns:[
            [
                {field:'name',title:'角色名称',align:'center',width:150},
                {field:'level',title:'角色等级',align:'center',width:120,
                    formatter:function (val, row, index) {
                        return format.get2name(format.get2dict('auth-level'), val);
                    }
                },
                {field:'module',title:'子系统',align:'left',width:300,
                    formatter:function (val, row, index) {
                        var module = '';
                        try{
                            $.each(val, function (index, obj) {
                                module += '[<span href="#" class="easyui-linkbutton" data-options="plain:true">'+obj.name+'</span>]&nbsp;'
                            })
                        }catch (ex){}
                        return module;
                    }
                },
                {field:'remark',title:'备注',align:'left',width:300}
            ]
        ]
    },
    form: {
        title: '角色操作',
        width:450,
        height:300,
        buttons: [{
            text:'保 存',
            iconCls:'icon-accept icon16',
            handler:function(){
                switch (optType){
                    case 1:
                        action.add();
                        break;
                    case 2:
                        action.edit();
                        break;
                }
            }
        },{
            iconCls:'icon-cancel icon16',
            text:'关 闭',
            handler:function(){
                component.dialog.close('#opt-form');
            }
        }]
    },
    auth: {
        title: '角色权限分配',
        width : kit.wh().width - 10,
        height : kit.wh().height - 10,
        left : 10,
        buttons: [{
            text:'保 存',
            iconCls:'icon-accept icon16',
            handler:function(){
                var menuArray = [];
                $.each(menuData, function (index, obj) {
                    var table = '#table-' + obj.code;
                    var checked = $(table).tree('getChecked');
                    var tem = {code: obj.code, menus: checked};
                    menuArray.push(tem);
                })
                var btns = [], menuIds = [];
                $('.btn-group').each(function () {
                    var checked = $(this).is(':checked');
                    if(checked){
                        var btn = $(this).attr('date-val').split('-');
                        var obj = {menuId: btn[0], buttonId: btn[1]};
                        menuIds.push(btn[0]);
                        btns.push(obj);
                    }
                })
                // 重组btns数据
                var btnItems = [];
                if(menuIds.length > 0){
                    menuIds = $.unique(menuIds);
                    $.each(menuIds, function (i, menuId) {
                        var btnArr = [];
                        $.each(btns, function (j, btn) {
                            if(btn.menuId == menuId){
                                btnArr.push(btn.buttonId);
                            }
                        })
                        var tem = {menuId: menuId, btns: btnArr};
                        btnItems.push(tem);
                    })
                }
                
                // 处理菜单数据
                var menuItems = [];
                if(menuArray.length > 0){
                    $.each(menuArray, function (i, objs) {
                        var parentArray = [];

                        $.each(objs.menus, function (j, obj) {
                            if(obj.parentId != 0){
                                parentArray.push(obj.parentId);
                                var tem = {menuId: obj.id, parentId: obj.parentId, btns:[]};
                                // 组合菜单和按钮数据
                                $.each(btnItems, function (k, btns) {
                                    if(btns.menuId == obj.id){
                                        tem.btns = btns.btns;
                                    }
                                })
                                menuItems.push(tem)
                            }
                        })
                        parentArray = $.unique(parentArray);

                        $.each(parentArray, function (k, parentId) {
                            var tem = {menuId: parentId, parentId: 0, btns:[]};
                            menuItems.push(tem)
                        })

                    })
                }
                var param = {
                    url: constant.route.role + '/auth/' + optRow.id,
                    data: menuItems
                };
                var request = http.put(param);
                request.done(function (d) {
                    kit.log(d.message);
                    component.dialog.close('#opt-form-auth');
                })
            }
        },{
            iconCls:'icon-cancel icon16',
            text:'关 闭',
            handler:function(){
                component.dialog.close('#opt-form-auth');
            }
        }]
    }
}

$(function () {
    component.datagrid.init('#table-list', config.table);
    action.get();
})

var opt = {
    add:function (_event) {
        optType = 1;
        component.dialog.init('#opt-form', config.form);
        component.dialog.open('#opt-form');
        kit.form.clean('#opt-form-data');
        opt.initCombobox();
    },
    edit:function () {
        if(optRow == null){
            kit.alert('请先选择一条数据', 'warning');
            return false;
        }
        config.form.title = '修改角色信息';
        optType = 2;
        component.dialog.init('#opt-form', config.form);
        component.dialog.open('#opt-form');
        kit.form.set('#opt-form-data', optRow);
        opt.initCombobox();
        kit.log(kit.json.attr2array(optRow.module, 'id'))
        $('#role-module').combobox('setValues', kit.json.attr2array(optRow.module, 'moduleId'));
    },
    delete:function () {
        if(optRow == null){
            kit.alert('请先选择一条数据', 'warning');
            return false;
        }
        var fun = "action.delete();";
        var c = {title: '删除角色', message: '确定要删除这个角色吗？', submit: fun }
        kit.confirm(c);
    },
    initCombobox: function () {
        kit.log(format.get2dict('auth-level'))
        component.combobox.init('#role-level', format.get2dict('auth-level'));
        component.combobox.setValue('#role-level', format.get2dict('auth-level')[0].code);
        component.combobox.init2('#role-module', store.get('sys-common-module'), 'id');
    },
    auth:function () {
        if(optRow == null){
            kit.alert('请先选择一条数据', 'warning');
            return false;
        }

        var module = optRow.module;
        $.each(module, function (index, obj) {
            var hasTab = $('#opt-form-auth-tab').tabs('exists', obj.name);
            if(!hasTab){
                $('#opt-form-auth-tab').tabs('add',{
                    title: obj.name,
                    content: '<div style="padding:10px"><span class="tree-loading">&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</span>' +
                    '<table id="table-'+obj.code+'" class="easyui-tree"></table></div>'
                });
            }
        })


        var param = {
            url: constant.route.role + '/auth/' + optRow.id
        };
        var request = http.get(param);
        request.done(function (d) {
            menuData = d.result;
            initMenuTree()
            component.dialog.init('#opt-form-auth', config.auth);
            component.dialog.open('#opt-form-auth');
            kit.render('#opt-form-auth');
        })
    }
}

function initMenuTree() {
    $.each(menuData, function (index, obj) {
        var table = '#table-' + obj.code;
        var data = obj.menus;
        var config = {
            checkbox:true,
            formatter:function(node){
                var s = '<div style="display: block; float: left; width: 100%;">' + node.text + '</div>';
                if (node.children){
                    var btns = '';
                    $.each(node.btns, function (i, o) {
                        var checked = '', color = 'ck-red';
                        if(o.checked == true){
                            checked = 'checked="checked"';
                            color = 'ck-green';
                        }
                        btns += '<span style="cursor: pointer;">' +
                            '<input '+checked+' type="checkbox" onclick="btn.style(this);"' +
                            'style="width: 16px; height: 16px;" class="btn-group" ' +
                            'date-val="'+o.menuId+'-'+o.buttonId+'" />' +
                            '<span onclick="btn.span(this);" class="' + color + '">' +o.name +
                            '&nbsp;</span></span>';
                    })
                    s += '<div style="display: block; float: left;">' + btns + '</div>';
                }
                return s;
            }
        }
        config.data = data;
        $(table).tree(config);
    })
    $('.tree-loading').html('');
}

var action = {
    get: function () {
        var param = {
            url: constant.route.role
        };
        var request = http.get(param);
        request.done(function (d) {
            component.datagrid.load('#table-list', d.result);
        })
    },
    add: function () {
        var data = kit.form.get('#opt-form-data');
        var modules = $('#role-module').combobox('getValues');
        data['module'] = modules;
        var param = {
            url: constant.route.role,
            data: data
        };
        var request = http.post(param);
        request.done(function (d) {
            var data = d.result;
            kit.form.clean('#opt-form-data');
            kit.alert(d.message, 'success');
            opt.initCombobox();
            component.datagrid.append('#table-list', data);
        })
    },
    edit: function () {
        var data = kit.form.get('#opt-form-data');
        var modules = $('#role-module').combobox('getValues');
        data['module'] = modules;
        data['id'] = optRow.id;
        var param = {
            url: constant.route.role,
            data: data
        };
        var request = http.put(param);
        request.done(function (d) {
            kit.alert(d.message, 'success');
            component.dialog.close('#opt-form');
            action.get();
        })
    },
    delete: function () {
        var param = {
            url: constant.route.role + '/' + optRow.id
        };
        var request = http.delete(param);
        request.done(function (d) {
            kit.alert(d.message, 'success');
            component.dialog.close('#opt-form');
            action.get();
        })
    }
}

var btn = {
    span:function (_event) {
        $(_event).parent().find('input').click();
    },
    style: function (_event) {
        var check = $(_event).is(":checked");
        if(check){
            $(_event).next().addClass('ck-green');
            $(_event).next().removeClass('ck-red');
        }else {
            $(_event).next().removeClass('ck-green');
            $(_event).next().addClass('ck-red');
        }
    }
}


